package cn.edu.sasu;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import cn.edu.sasu.domain.Weather;
import cn.edu.sasu.http.HttpUrl;
import cn.edu.sasu.utils.AnimationMove;
import cn.edu.sasu.webservice.NewsService;
import cn.edu.sasu.webservice.impl.NewsServiceImpl;

/**
 * 这个新闻启动的时候，处理导航的Activity
 * 
 * @author yubaolinfish
 * 
 */
@SuppressLint("HandlerLeak")
@SuppressWarnings("deprecation")
public class NewsActivity extends ActivityGroup {
	private RelativeLayout layout;
	private RelativeLayout layout_news_main;
	private Intent intent;
	private View page;// 用来存放顶部具体分类的view

	/**
	 * 需要移动的View
	 * 这是一个背景，当点击一个导航的时候，这个View就会作为一个动画移动到相应的位置，并且覆盖该导航上的文字，再把自己显示的文字修改了
	 */
	private TextView bgAnimation;

	private TextView tv_bar_news;
	private TextView tv_bar_sport;
	private TextView tv_bar_play;
	private TextView tv_bar_finance;
	private TextView tv_bar_science;
	private TextView tv_bar_more;
	private TextView new_title;
	/**
	 * 天气图片
	 */
	private ImageView weatherImage = null;
	/**
	 * 天气文字
	 */
	private TextView weatherText = null;

	/**
	 * 得到当前点击的导航的宽度，用来计算导航的位置（注意：这个宽度我们是以第一个导航（校园新闻）的值来确定的,因为后面的都是一样大的）
	 */
	private int schoolNews_width = 0;

	private LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
			LayoutParams.FILL_PARENT);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news);
		newsService = new NewsServiceImpl();
		new_title = (TextView) findViewById(R.id.new_title);

		init();
	}

	private void init() {
		weather();// 查询天气

		// 加载前五个导航标题（校园新闻，通知公告……）
		tv_bar_news = (TextView) findViewById(R.id.tv_title_bar_schoolNews);
		tv_bar_sport = (TextView) findViewById(R.id.tv_title_bar_newsNotice);
		tv_bar_play = (TextView) findViewById(R.id.tv_title_bar_newsMaidan);
		tv_bar_finance = (TextView) findViewById(R.id.tv_title_bar_cooperateCommunion);
		tv_bar_science = (TextView) findViewById(R.id.tv_title_bar_basicFacts);
		tv_bar_more = (TextView) findViewById(R.id.tv_title_bar_more);

		layout = (RelativeLayout) findViewById(R.id.layout_title_bar);// 加载新闻导航的相对布局
		layout_news_main = (RelativeLayout) findViewById(R.id.layout_news_main);// 加载新闻内容向

		// 注册监听事件，使用同一个监听器，判断是哪个点击的就可以了
		tv_bar_news.setOnClickListener(listener);
		tv_bar_sport.setOnClickListener(listener);
		tv_bar_play.setOnClickListener(listener);
		tv_bar_finance.setOnClickListener(listener);
		tv_bar_science.setOnClickListener(listener);
		tv_bar_more.setOnClickListener(listener);

		bgAnimation = new TextView(this);
		bgAnimation.setBackgroundResource(R.drawable.slidebar);// 设置背景图片（没有使用ImageView控件）
		bgAnimation.setTextColor(Color.WHITE);// 设置颜色
		bgAnimation.setText(this.getString(R.string.news_category_schoolNews));// “校园新闻”
		bgAnimation.setGravity(Gravity.CENTER);

		RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		param.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);

		layout.addView(bgAnimation, param);

		// 初始显示“校园新闻”
		layout_news_main.removeAllViews();

		weatherImage = (ImageView) findViewById(R.id.weatherImage);
		weatherText = (TextView) findViewById(R.id.weatherText);

		new_title.setText(R.string.news_category_schoolNews);
		intent = new Intent(NewsActivity.this, NewsSchoolNewsActivity.class);// 创建一个意图对象，集合显示校园新闻的Activity

		intent.putExtra("title", HttpUrl.URL_NEWS_SCHOOLNEWS);// 附带设置数据（“校园新闻”）

		page = getLocalActivityManager().startActivity("activity1", intent)
				.getDecorView();// 返回对象Activity的View（界面）

		layout_news_main.addView(page, params);// 把返回回来的界面添加到我们的显示区域中

	}

	private NewsService newsService = null;

	private void weather() {
		// 首先判断网络是否正常（笔者做的是平板应用的一个模块有手机有些功能不一样）
		WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		if (wm.isWifiEnabled()) {
			Weather.setWeather("暂无天气信息");
			return;
		}

		new Thread() {
			@Override
			public void run() {
				try {

					newsService.resquestWeather();// 获取天气信息，并保存到Weather类中

					handler.sendEmptyMessage(1);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();

	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:

				/**
				 * 这个地方是处理天气信息的地方，要说明的是调用的天气的webservice是需要付费使用的，
				 * 所以我这个地方可以会出现地区不准的问题
				 */
				Resources resources = getResources();

				String image = Weather.getWeatherInfo()[10];
				if (image == null || "".equals(image)) {
					image = "2.gif";
				}
				int i = resources.getIdentifier(
						"a_" + image.substring(0, image.lastIndexOf(".")),
						"drawable", getPackageName());

				weatherImage.setBackgroundResource(i);

				// 今日天气实况：气温：21℃；风向/风力：西北风 1级；湿度：68%
				try {
					weatherText.setText(Weather.getWeatherInfo()[1]
							+ ": "
							+ Weather.getWeatherInfo()[4].substring(7,
									Weather.getWeatherInfo()[4].length() - 20));
				} catch (Exception e) {
					weatherText.setText("达州天气 " + ": " + "晴朗");
					e.printStackTrace();
				}
				break;

			default:
				break;
			}
		};
	};

	private OnClickListener listener = new OnClickListener() {
		int startX;// 移动的起始位置

		@Override
		public void onClick(View v) {

			// 得到当前点击的导航的宽度，用来计算导航的位置（注意：这个宽度我们是以第一个导航（校园新闻）的值来确定的,因为后面的都是一样大的）
			schoolNews_width = findViewById(R.id.schoolNews_relative)
					.getWidth();

			switch (v.getId()) {
			case R.id.tv_title_bar_schoolNews:// 校园新闻

				new_title.setText(R.string.news_category_schoolNews);
				AnimationMove.moveFrontBg(bgAnimation, startX, 0, 0, 0);// 开始动画
				startX = 0;// 记录当前动画背景的位置，（左上角）
				bgAnimation.setText(R.string.news_category_schoolNews);// 在给背景设置相应的文字，因为这个背景是要覆盖我们当前点击的导航上的文字的

				// page = inflater.inflate(R.layout.news_school, null);

				// 处理要显示的内容
				intent.setClass(NewsActivity.this, NewsSchoolNewsActivity.class);
				intent.putExtra("title", HttpUrl.URL_NEWS_SCHOOLNEWS);// 这个“title”传递过去根本就米有用过，传的就是一个没有的数据
				page = getLocalActivityManager().startActivity("activity1",
						intent).getDecorView();
				break;
			case R.id.tv_title_bar_newsNotice:

				new_title.setText(R.string.news_category_notice);
				AnimationMove.moveFrontBg(bgAnimation, startX,
						schoolNews_width, 0, 0);
				startX = schoolNews_width;

				bgAnimation.setText(R.string.news_category_notice);

				// 准备显示“通知公告”
				// 处理要显示的内容
				intent.setClass(NewsActivity.this, NewsNoticeActivity.class);
				intent.putExtra("title", HttpUrl.URL_NEWS_NOTICE);
				page = getLocalActivityManager().startActivity("activity2",
						intent).getDecorView();
				break;
			case R.id.tv_title_bar_newsMaidan:

				new_title.setText(R.string.news_category_maidan);
				AnimationMove.moveFrontBg(bgAnimation, startX,
						schoolNews_width * 2, 0, 0);
				startX = schoolNews_width * 2;
				bgAnimation.setText(R.string.news_category_maidan);
				// 准备显示“文理广场”
				intent.setClass(NewsActivity.this, NewsMaidanActivity.class);
				intent.putExtra("title", HttpUrl.URL_NEWS_MAIDAN);
				page = getLocalActivityManager().startActivity("activity3",
						intent).getDecorView();
				break;
			case R.id.tv_title_bar_cooperateCommunion:

				new_title.setText(R.string.news_category_cooperateCommunion);
				AnimationMove.moveFrontBg(bgAnimation, startX,
						schoolNews_width * 3, 0, 0);
				startX = schoolNews_width * 3;
				bgAnimation.setText(R.string.news_category_cooperateCommunion);
				// 准备显示“合作交流”
				intent.setClass(NewsActivity.this,
						NewsCooperateCommunionActivity.class);
				intent.putExtra("title", HttpUrl.URL_NEWS_COOPERATECOMMUNION);
				page = getLocalActivityManager().startActivity("activity4",
						intent).getDecorView();
				break;
			case R.id.tv_title_bar_basicFacts:// 点击“学院概况”的时候

				new_title.setText(R.string.news_category_basicFacts);
				AnimationMove.moveFrontBg(bgAnimation, startX,
						schoolNews_width * 4, 0, 0);
				startX = schoolNews_width * 4;
				bgAnimation.setText(R.string.news_category_basicFacts);
				// 准备显示“学院概况”
				intent.setClass(NewsActivity.this, NewsBasicFactsActivity.class);
				intent.putExtra("title", HttpUrl.URL_NEWS_BASICFACTS);
				page = getLocalActivityManager().startActivity("activity5",
						intent).getDecorView();
				break;
			case R.id.tv_title_bar_more:// 点击“更多”的时候

				new_title.setText(R.string.news_category_more);
				AnimationMove.moveFrontBg(bgAnimation, startX,
						schoolNews_width * 5, 0, 0);// 点击更多的时候，首先显示背景动画
				startX = schoolNews_width * 5;
				bgAnimation.setText(R.string.news_category_more);
				// 准备显示“更多”
				intent.setClass(NewsActivity.this, NewsMoreActivity.class);
				// page = getLocalActivityManager().startActivity("activity6",
				// intent).getDecorView();
				startActivity(intent);

				break;
			}
			// 切换
			layout_news_main.removeAllViews();
			layout_news_main.addView(page, params);

		}
	};

	@Override
	public boolean onTouchEvent(android.view.MotionEvent event) {
		float startX = 0;
		// 处理手势滑动的效果
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:// 手势按下的时候
			startX = event.getX();
			break;
		case MotionEvent.ACTION_MOVE:// 手势移动的时候

			break;
		case MotionEvent.ACTION_UP:// 手势松开的时候
			float endX = event.getX();
			if (endX > startX) {// 向右滑动

			} else if (endX < startX) {// 向左滑动

			} else {

			}

			break;

		}

		return false;

	};

	/**
	 * 您确定要退出程序吗
	 */
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("确认退出文理新闻吗？").setIcon(R.drawable.sasu_logo)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 点击“确认”后的操作
						finish();
						System.exit(0);// 否则退出程序
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 点击“返回”后的操作,这里不设置没有任何操作
					}
				}).show();
	};

}
